<template>
  <el-card>
    <!-- 搜索框 -->
    <el-row :gutter="20" class="header">
      <el-col :span="7">
        <el-input placeholder="请输入试卷名称" clearable v-model="queryForm.query"></el-input>
      </el-col>
      <el-button type="primary" :icon="Search" @click="initGetTestPaperlist">搜索</el-button>
      <el-button type="primary" @click="addDialog">添加试卷</el-button>
    </el-row>
    <!-- 筛选 -->
    <el-row :gutter="20" class="header">
      <el-select v-model="queryForm.subjectValue" class="m-2" placeholder="请选择科目">
        <el-option
          v-for="item in queryForm.subject"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" :icon="Search" @click="screen">筛选</el-button>
    </el-row>
    <!-- 表单 -->
    <el-table :data="tableData" style="width: 100%" border stripe>
      <el-table-column label="创建时间" show-overflow-tooltip>
        <template #default="scope">
          {{ getNowDate(scope.row.time) }}
        </template>
      </el-table-column>>
      <el-table-column prop="subject" label="科目"  />
      <el-table-column prop="testpaper" label="试卷名称" show-overflow-tooltip />
      <el-table-column prop="questionIds" label="题目编号" show-overflow-tooltip/>
      <el-table-column label="分值">
        <template #default="scope">
          {{ score(scope.row.scores) }}
        </template>
      </el-table-column>>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="scope">
          <el-button size="small" @click="opendialog(scope.row)">详情</el-button>
          <el-button type="primary" size="small" @click="opendialogoption(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="deletetestpaper(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      :page-size="queryForm.pagesize"
      :pager-count="5"
      layout="prev, pager, next"
      :total="queryForm.totle"
      :hide-on-single-page="queryForm.pagesize>=queryForm.totle"
      @current-change="handleCurrentChange"
      :current-page="queryForm.pagename"
    />
  </el-card>
  <!-- 试卷详情 -->
  <el-dialog
    v-model="dialogVisible"
    title="试卷详情"
    width="80%"
  >
      <el-table :data="questionlist" stripe style="width: 100%" border max-height="350">
        <el-table-column prop="id" label="编号" width="60px"/>
        <el-table-column prop="title" label="题目" show-overflow-tooltip />
        <el-table-column prop="subject" label="科目" width="90px"/>
        <el-table-column label="类型" width="90px">
          <template #default="scope">
            {{ changeType(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="选项" show-overflow-tooltip >
          <template #default="scope">
            <span v-for="item in scope.row.options" :key="item">{{ item.code }}.{{ item.option }};</span>
          </template>
        </el-table-column>
        <el-table-column prop="answer" label="答案" show-overflow-tooltip />
        <el-table-column prop="analysis" label="解析" show-overflow-tooltip />
        <el-table-column prop="score" label="分值" />
      </el-table>
  </el-dialog>
  <!-- 编辑试卷-->
  <el-dialog
    v-model="dialogOption"
    title="编辑试卷"
    width="80%"
    :show-close="false"
    @close="closeDialogOption"
  >
    <el-row :gutter="20" class="header">
      <el-col :span="14" style="display: flex; align-items: center;">
        <div style="flex: 1; font-weight: bold;">试卷名称：</div><el-input style="flex: 3" placeholder="请输入试卷名词" clearable v-model="testpaperInfo.testpaper"></el-input>
      </el-col>
      <el-select v-model="testpaperInfo.subject" class="m-2" placeholder="请选择科目">
        <el-option
          v-for="item in subjectlist"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-row>
    <hr style="margin-bottom: 10px;">
    <!-- 搜索框 -->
    <el-row :gutter="20" class="header" v-if="!isScore">
      <el-col :span="7">
        <el-input placeholder="请输入题目/答案/解析" clearable v-model="dialogQuery.query"></el-input>
      </el-col>
      <el-button type="primary" :icon="Search" @click="initGetQuestionlist">搜索</el-button>
    </el-row>
    <!-- 筛选 -->
    <el-row :gutter="20" class="header" v-if="!isScore">
      <el-select v-model="dialogQuery.subjectValue" class="m-2" placeholder="请选择科目">
        <el-option
          v-for="item in dialogQuery.subject"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="dialogQuery.typeValue" class="m-2" placeholder="请选择类型">
        <el-option
          v-for="item in dialogQuery.type"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" :icon="Search" @click="dialogScreen">筛选</el-button>
    </el-row>
    <!-- 选择试题 -->
    <el-table v-if="!isScore" :row-key="(row) => { return row.id }"  ref="DialogTableData" :data="dialogTableData" stripe style="width: 100%" border max-height="250" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40px" :reserve-selection="true" />
      <el-table-column prop="id" label="编号" width="60px"/>
      <el-table-column prop="title" label="题目" show-overflow-tooltip />
      <el-table-column prop="subject" label="科目" width="90px"/>
      <el-table-column label="类型" width="90px">
        <template #default="scope">
          {{ changeType(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="选项" show-overflow-tooltip >
        <template #default="scope">
          <span v-for="item in scope.row.options" :key="item">{{ item.code }}.{{ item.option }};</span>
        </template>
      </el-table-column>
      <el-table-column prop="answer" label="答案" show-overflow-tooltip />
      <el-table-column prop="analysis" label="解析" show-overflow-tooltip />
    </el-table>
    <!-- 设置分数 -->
    <el-table v-if="isScore" :data="testpaperInfo.questionlist" stripe style="width: 100%" border max-height="350" >
      <el-table-column prop="id" label="编号" width="60px"/>
      <el-table-column prop="title" label="题目" show-overflow-tooltip />
      <el-table-column prop="subject" label="科目" width="90px"/>
      <el-table-column label="类型" width="90px">
        <template #default="scope">
          {{ changeType(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="选项" show-overflow-tooltip >
        <template #default="scope">
          <span v-for="item in scope.row.options" :key="item">{{ item.code }}.{{ item.option }};</span>
        </template>
      </el-table-column>
      <el-table-column prop="answer" label="答案" show-overflow-tooltip />
      <el-table-column prop="analysis" label="解析" show-overflow-tooltip />
      <el-table-column label="分值" >
        <template #default="scope">
          <el-input type="text" v-model="scope.row.score" />
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button type="primary" v-if="!isScore" @click="ToScore">设置分数</el-button>
      <el-button v-if="isScore" @click="BcakScore">返回选择试题</el-button>
      <el-button type="primary" v-if="isScore" @click="summit">提交编辑</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
  import { Search } from '@element-plus/icons-vue'
  import { ref, nextTick, computed } from 'vue'
  import { getalltestpaperlist, getquestions, getquestionlist, settestpaper, deltestpaper } from '@/api/question'
  import { ElMessage, ElMessageBox } from 'element-plus'

  const queryForm = ref({
    query: '',
    subject: [],
    subjectValue: '',
    pagename: 1,
    pagesize: 4,
    totle: 0
  })
  const tableData = ref([])
  const testpaperlist = ref([])
  const resultlist = ref([])

  // 总分值
  const score = computed(() => (scores) => {
    let result = 0
    for (let i = 0; i < scores.length; i++) {
      result += scores[i] - 0
    }
    return result
  })

  // 查询问题列表
  const initGetTestPaperlist = async () => {
    // console.log(queryForm.value.query)
    const res = await getalltestpaperlist({
      param: queryForm.value.query
    })
    // console.log(res.testpaperlist)
    testpaperlist.value = res.testpaperlist
    resultlist.value = res.testpaperlist
    queryForm.value.totle = res.testpaperlist.length
    const arr = []
    for (let i = 0; i < res.subjectlist.length; i++) {
      arr.push({ label: res.subjectlist[i], value: res.subjectlist[i] })
    }
    arr.push({ label: '全部科目', value: '' })
    queryForm.value.subject = arr
    handleCurrentChange(1)
  }
  // 分页展示表格
  const initTableData = () => {
    const start = (queryForm.value.pagename - 1) * queryForm.value.pagesize
    let end = queryForm.value.pagename * queryForm.value.pagesize
    end = end < queryForm.value.totle ? end : queryForm.value.totle
    const arr = []
    for (let i = start; i < end; i++) {
      arr.push(resultlist.value[i])
    }
    tableData.value = arr
  }
  initGetTestPaperlist()
  // 改变分页
  const handleCurrentChange = (number) => {
    queryForm.value.pagename = number
    initTableData()
  }

  // 筛选
  const screen = () => {
    const arr = []
      for (let i = 0; i < testpaperlist.value.length; i++) {
        if (testpaperlist.value[i].subject.indexOf(queryForm.value.subjectValue) !== -1) {
          arr.push(testpaperlist.value[i])
        }
      }
    queryForm.value.totle = arr.length
    resultlist.value = arr
    handleCurrentChange(1)
  }

  const questionlist = ref([])
  const dialogVisible = ref(false)
  // 获取问题列表
  const opendialog = (row) => {
    dialogVisible.value = true
    getquestions({
      questionIds: row.questionIds
    }).then(res => {
      questionlist.value = res.questions
      for (let i = 0; i < res.questions.length; i++) {
        const index = row.questionIds.indexOf(res.questions[i].id)
        questionlist.value[i].score = row.scores[index]
      }
    })
  }

  // 转换题目类型
  const changeType = (str) => {
    switch (str) {
      case 'tian': return '填空题'
      case 'duo': return '多选题'
      case 'pan': return '判断题'
      case 'dan': return '单选题'
    }
  }

  // 编辑试卷部分
  const dialogOption = ref(false)
  const dialogQuery = ref({
    query: '',
    subject: [],
    subjectValue: '',
    type: [
      { label: '多选题', value: 'duo' },
      { label: '单选题', value: 'dan' },
      { label: '填空题', value: 'tian' },
      { label: '判断题', value: 'pan' },
      { label: '请选择类型', value: '' }
    ],
    typeValue: ''
  })
  const dialogTableData = ref([])
  const dialogQuestionlist = ref([])
  const isInit = ref(true) // 用于初始化回显数据时取消handleSelectionChange函数操作
  // 查询问题列表
  const initGetQuestionlist = async () => {
    // console.log(queryForm.value.query)
    const res = await getquestionlist({
      param: dialogQuery.value.query
    })
    // console.log(res.subjectlist)
    const arr = []
    for (let i = 0; i < res.subjectlist.length; i++) {
      arr.push({ label: res.subjectlist[i].subject, value: res.subjectlist[i].subject })
    }
    subjectlist.value = JSON.parse(JSON.stringify(arr))
    arr.push({ label: '请选择科目', value: '' })
    dialogQuery.value.subject = arr
    dialogQuery.value.typeValue = ''
    dialogQuery.value.subjectValue = ''
    dialogQuestionlist.value = res.questionlist
    dialogTableData.value = res.questionlist

    nextTick(() => {
      const list = []
      for (let i = 0; i < dialogTableData.value.length; i++) {
        if (testpaperInfo.value.questionIds.indexOf(dialogTableData.value[i].id) !== -1) {
          DialogTableData.value.toggleRowSelection(dialogTableData.value[i], true)
          list.push(dialogTableData.value[i])
        } else {
          DialogTableData.value.toggleRowSelection(dialogTableData.value[i], false)
        }
      }
      testpaperInfo.value.questionlist = list
      isInit.value = false
    })
  }

  // 筛选
  const dialogScreen = () => {
    const arr = []
    for (let i = 0; i < dialogQuestionlist.value.length; i++) {
      if (dialogQuestionlist.value[i].subject.indexOf(dialogQuery.value.subjectValue) !== -1 && dialogQuestionlist.value[i].type.indexOf(dialogQuery.value.typeValue) !== -1) {
        arr.push(dialogQuestionlist.value[i])
      }
    }
    dialogTableData.value = arr
  }
  // 编辑试卷弹窗部分内容
  const testpaperInfo = ref({
    subject: '',
    testpaper: '',
    questionIds: [],
    questionlist: [],
    scores: [],
    time: 0
  })
  // const subject = ref('')
  const subjectlist = ref([])
  // const testpaper = ref('')
  // 打开编辑试卷时的操作
  const opendialogoption = (item) => {
    // subject.value = item.subject
    // testpaper.value = item.testpaper
    dialogOption.value = true
    // console.log('item', item)
    testpaperInfo.value = JSON.parse(JSON.stringify(item))
    initGetQuestionlist()
  }
  // 多选框改变
  const DialogTableData = ref(null) // 替代 vue2的 this.$ref获取DOM节点
  const handleSelectionChange = (checkArr) => {
    if (isInit.value) return
    // console.log(checkArr)
    // 选中操作
    if (checkArr.length > testpaperInfo.value.questionIds.length) {
      for (let i = 0; i < checkArr.length; i++) {
        if (testpaperInfo.value.questionIds.indexOf(checkArr[i].id) === -1) {
          testpaperInfo.value.questionIds.push(checkArr[i].id)
          testpaperInfo.value.questionlist.push(checkArr[i])
          testpaperInfo.value.scores.push(2)
        }
      }
    } else {
      // 取消选中操作
      const checkIds = []
      for (let k = 0; k < checkArr.length; k++) {
        checkIds.push(checkArr[k].id)
      }
      // console.log('1', checkIds)
      // console.log('2', testpaperInfo.value.questionIds)
      for (let i = 0; i < testpaperInfo.value.questionIds.length; i++) {
        if (checkIds.indexOf(testpaperInfo.value.questionIds[i].id) === -1) {
          testpaperInfo.value.questionIds.splice(i, 1)
          testpaperInfo.value.questionlist.splice(i, 1)
          testpaperInfo.value.scores.splice(i, 1)
          break
        }
      }
    }
    // console.log(testpaperInfo.value.questionIds)
    // console.log(testpaperInfo.value.scores)
  }
  // 关闭弹窗
  const closeDialogOption = () => {
    testpaperInfo.value = {
      subject: '',
      testpaper: '',
      questionIds: [],
      questionlist: [],
      scores: []
    }
    isInit.value = true
    dialogOption.value = false
    // subject.value = ''
    // testpaper.value = ''
    isScore.value = false
    isAdd.value = false
  }
  // 设置分数
  const isScore = ref(false)
  const ToScore = () => {
    isScore.value = true
    isInit.value = true
    for (let i = 0; i < testpaperInfo.value.questionlist.length; i++) {
      testpaperInfo.value.questionlist[i].score = testpaperInfo.value.scores[i]
    }
  }
  const BcakScore = () => {
    isScore.value = false
    initGetQuestionlist()
  }
  // 提交
  const summit = () => {
    // console.log(testpaperInfo)
    // console.log(subject)
    // console.log(testpaper)
    ElMessageBox.confirm(
      '是否提交该试卷？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    .then(() => {
      if (testpaperInfo.value.subject.split(' ').join('') === '' || testpaperInfo.value.testpaper.split(' ').join('') === '') {
        return ElMessage.error('科目或试卷名称不能为空')
      }
      if (testpaperInfo.value.questionlist.length === 0) {
        return ElMessage.error('未选择题目')
      }
      const item = {
        subject: testpaperInfo.value.subject,
        testpaper: testpaperInfo.value.testpaper,
        questionlist: testpaperInfo.value.questionlist
      }
      if (!isAdd.value) {
        item.time = testpaperInfo.value.time
      }
      settestpaper(item).then(res => {
        ElMessage.success(res.msg)
        initGetTestPaperlist()
        closeDialogOption()
      })
    })
    .catch(() => {})
  }
  const isAdd = ref(false)
  // 添加试卷打开编辑试卷对话框
  const addDialog = () => {
    dialogOption.value = true
    isAdd.value = true
    initGetQuestionlist()
  }
  // 获取时间
  const getNowDate = computed(() => (time) => {
    const date = new Date(time)
    const sign2 = ':'
    const year = date.getFullYear() // 年
    let month = date.getMonth() + 1 // 月
    let day = date.getDate() // 日
    let hour = date.getHours() // 时
    let minutes = date.getMinutes() // 分
    let seconds = date.getSeconds() // 秒
    // let weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
    // let week = weekArr[date.getDay()];
    // 给一位数的数据前面加 “0”
    if (month >= 1 && month <= 9) {
    month = '0' + month
    }
    if (day >= 0 && day <= 9) {
    day = '0' + day
    }
    if (hour >= 0 && hour <= 9) {
    hour = '0' + hour
    }
    if (minutes >= 0 && minutes <= 9) {
    minutes = '0' + minutes
    }
    if (seconds >= 0 && seconds <= 9) {
    seconds = '0' + seconds
    }
    return year + '-' + month + '-' + day + ' ' + hour + sign2 + minutes + sign2 + seconds
  })
  // 删除试卷
  const deletetestpaper = (row) => {
    ElMessageBox.confirm(
      '是否删除该试卷',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    .then(() => {
      deltestpaper({
        subject: row.subject,
        testpaper: row.testpaper,
        time: row.time
      }).then(res => {
        ElMessage.success(res.msg)
        initGetTestPaperlist()
      })
    })
    .catch(() => {})
  }
</script>

<style lang="scss" scoped>
  .header {
    padding-bottom: 16px;
    box-sizing: border-box;
  }
  ::v-deep .el-image {
    width: 50px;
    height: 50px;
    border-radius: 50%;
  }
  ::v-deep .el-pagination {
    display: flex;
    justify-content: center;
    margin-top: 16px;
  }
  .m-2 {
    margin: 0 10px;
  }
  ::v-deep .warning-row {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
  }
</style>
